package com.lib.application;

import com.lib.model.ShopQRCode;
import com.lib.repository.ShopQRCodeRepository;
import com.lib.service.WxAgentService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by duqingxiang on 17/5/24.
 */
@Service
public class ShopQRCodeService {

    @Autowired
    ShopQRCodeRepository shopQRCodeRepository;

    @Autowired
    WxAgentService wxAgentService;

    public String saveShopQRCode(long shopId,String shopName) {

        ShopQRCode code = shopQRCodeRepository.findShopQRCodeByShopId(shopId);
        if (code != null) {
            code.setShopName(shopName);
        } else {
            code = ShopQRCode.builder()
                    .shopId(shopId)
                    .shopName(shopName)
                    .build();
            code = shopQRCodeRepository.saveAndFlush(code);
        }

        try {

            //门店二维码生成  其实是在经纪人的公众号上生成的，扫码也是针对经纪人用的
            WxMpQrCodeTicket ticket = wxAgentService.getQrcodeService().qrCodeCreateLastTicket(code.getId());

            code.setExpireSeconds(ticket.getExpire_seconds());
            code.setTicket(ticket.getTicket());
            code.setUrl(ticket.getUrl());
            code.setModifyDate(new Date());

            code = shopQRCodeRepository.saveAndFlush(code);
            return code.getTicket();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public String getShopQRCode(long shopId) {
        ShopQRCode code = shopQRCodeRepository.findShopQRCodeByShopId(shopId);
        if (code == null)
            return null;
        return code.getTicket();
    }

}
